﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Resources;
using System.Text;
using System.Windows.Forms;
using System.Xml;

//using t_vips_analizator;


namespace monitor_2_DBwork
{

    public class DeviceInfo
    {
        public string DeviceName;
        public string DeviceRtps;
        public bool Active;

        public new string ToString()
        {
            return DeviceRtps + "_" + DeviceName;
        }
    }

    public class StringValue : Attribute
    {
        private readonly string _value;

        public StringValue(string value)
        {
            _value = value;
        }

        public string Value
        {
            get { return _value; }
        }

    }
    public enum ServerCategories
    {
        [StringValue("LoginServerCategory")]
        Login = 1,
        [StringValue("InfoServerCategory")]
        Info = 2,
        [StringValue("WarningServerCategory")]
        Warning = 3,
        [StringValue("SystemErrorServerCategory")]
        SystemError = 4
    }

    public class DBwork
    {
        public static readonly ResourceManager ResourceManager = new ResourceManager(typeof(monitor_2_DBwork));

        public static bool CheckConnection()
        {
            return DBRepository<BLR>.CheckConnection();
        }

        public static string AddUser(string login, string pw, string access, string info)
        {
            var users = new DBRepository<Users>();
            Users user;
            try
            {
                user = new Users(login, pw, int.Parse(access), info);
            }
            catch
            {
                return "err:" + ResourceManager.GetString("WrongParameters");
            }

            return users.Add(user) ? "ok" : "err:" + ResourceManager.GetString("OperationError");
                
        }

        public static string AddIzmerStatisticsRecord(string curValue, string etalonValue, DateTime date, string ip)
        {
            var isrs = new DBRepository<IzmersStatistics>();
            IzmersStatistics isr;
            using (var session = NHibernateHelper.Create().Session)
            {
                isr = new IzmersStatistics
                    {
                        CurrentValue = curValue,
                        Etalon = etalonValue,
                        Date = date,
                        Iddevice = session.CreateQuery("FROM Devices WHERE IPAddress = :ip").SetString("ip", ip).UniqueResult<Devices>().Id
                    };
            }
            return isrs.Add(isr) ? "ok" : "err:" + ResourceManager.GetString("OperationError")
                + ". " + ResourceManager.GetString("saveIzmerStat") + ": " + ip;
        }

        public static string DelUser(string login)
        {
            var users = new DBRepository<Users>();

            var user = new Users { Name = login };

            return users.Remove(user) ? "ok" : "err:" + ResourceManager.GetString("OperationError");
        }

        public static string UpdateUserWithoutPassword(string dellogin, string login, string access, string info)
        {
            var pw = (new DBRepository<Users>()).GetItem(dellogin).PasswordHashCode.ToString();
            string str = DelUser(dellogin);
            if (str != "ok")
                return str;
            str = AddUser(login, pw, access, info);
            return str;
        }

        public static string UpdateUser(string dellogin, string login, string pw, string access, string info)
        {
            string str = DelUser(dellogin);
            if (str != "ok")
                return str;
            str = AddUser(login, pw, access, info);
            return str;
        }

        /// <summary>
        /// Проверяет наличие записи о пользователе в базе.
        /// </summary>
        /// <param name="name">Имя пользователя.</param>
        /// <returns></returns>
        public static string CheckUserExistance(string name)
        {
            try
            {
                using (var session = NHibernateHelper.Create().Session)
                {
                    var query = session.CreateQuery("FROM Users WHERE Login = :login").SetString("login", name);
                    var list = query.List<Users>();
                    session.Close();
                    return list.Count > 0 ? "1" : "0";
                }
            }
            catch (Exception ex)
            {
                if (ex.Message == "Object reference not set to an instance of an object.")
                    return "err:" + ResourceManager.GetString("NoDBConnection");
                return "err:" + ex.Message;
            }
        }

        /// <summary>
        /// Проверяет наличие записи о станции в базе.
        /// </summary>
        /// <param name="name">Название станции.</param>
        /// <returns></returns>
        public static string CheckStationExistance(string name)
        {
            try
            {
                using (var session = NHibernateHelper.Create().Session)
                {
                    var query = session.CreateQuery("FROM RTPS WHERE Name = :stationName").SetString("stationName", name);
                    var list = query.List<RTPS>();
                    session.Close();
                    return list.Count > 0 ? "1" : "0";
                }
            }
            catch (Exception ex)
            {
                if (ex.Message == "Object reference not set to an instance of an object.")
                    return "err:" + ResourceManager.GetString("NoDBConnection");
                return "err:" + ex.Message;
            }
        }

        /// <summary>
        /// Определяет тип доступа пользователя.
        /// </summary>
        /// <param name="name">Имя пользователя.</param>
        /// <param name="pw">Пароль пользователя.</param>
        /// <returns>0 - доступ запрещен; 1 - администратор; 2 - пользователь.</returns>
        public static string CheckPassword(string name, string pw)
        {
            try
            {
                using (var session = NHibernateHelper.Create().Session)
                {
                    var query = session.CreateQuery("FROM Users WHERE Login = :login").SetString("login", name);
                    var list = query.List<Users>();
                    session.Close();
                    if (list.Count > 0)
                        if (pw.GetHashCode() == list[0].PasswordHashCode)
                            //return list[0].AccessInfo.Name;
                            return list[0].Access.ToString(CultureInfo.InvariantCulture);
                    return "0";
                }
            }
            catch (Exception ex)
            {
                if (ex.Message == "Object reference not set to an instance of an object.")
                    return "err:" + ResourceManager.GetString("NoDBConnection");
                return "err:" + ex.Message;
            }
        }

        /// <summary>
        /// Определяет область, из которой логиниться клиент.
        /// </summary>
        /// <param name="ip"></param>
        /// <returns>Имя области, если ip-адрес есть в списке доверенных. Иначе - notExist</returns>
        public static string CheckTrustedAddress(string ip)
        {
            var address = new DBRepository<TrustedAddress>();
            TrustedAddress ret;
            try
            {
                ret = address.GetItem(ip);
            }
            catch (Exception)
            {
                return "err:";
            }

            return ret != null ? ret.Oblast.Name : "notExist";
        }

        public static string TreeToXml(string oblast, out string xmlFile)
        {
            var xmlWriter = new StringWriter();
            xmlFile = string.Empty;
            var deviceTree = new List<Oblast>(1);
            try
            {
                using (var s = NHibernateHelper.Create().Session)
                {
                    using (var tr = s.BeginTransaction())
                    {
                        if (oblast != "all")
                        {
                            var oblList = s.CreateQuery("FROM Oblast WHERE Name = :obl").SetString("obl", oblast).UniqueResult<Oblast>();
                            deviceTree.Add(oblList);
                        }
                        else
                        {
                            deviceTree = (List<Oblast>)s.CreateQuery("FROM Oblast").List<Oblast>();
                        }
                        tr.Commit();
                    }

                    //----------------

                    //if (xmlPath == null)
                    //    return "err:" + ResourceManager.GetString("NoPath");
                    //string _deviceTreeNamespace = "http://tempuri.org/DeviceTree.xsd";

                    //XmlWriterSettings xmlSettings = new XmlWriterSettings();

                    try
                    {
                        var xs = new XmlWriterSettings();
                        xs.Encoding = Encoding.UTF8;
                        xs.OmitXmlDeclaration = true;
                        using (var xml = XmlWriter.Create(xmlWriter,xs))
                        {
                            xml.WriteStartElement("Regions");
                            foreach (var obl in deviceTree)
                            {
                                xml.WriteStartElement("Region");
                                xml.WriteAttributeString("Name", obl.Name);
                                //xml.WriteElementString("RegionName", obl.Name);

                                foreach (RTPS rtps in obl.RTPSList)
                                {
                                    xml.WriteStartElement("RTPS");
                                    xml.WriteAttributeString("Name", rtps.Name);
                                    xml.WriteAttributeString("BLR", rtps.BLR.Name);
                                    xml.WriteAttributeString("Coordinates", rtps.Coordinates);

                                    foreach (Devices dev in rtps.DeviceList)
                                    {
                                        xml.WriteStartElement("Device");
                                        xml.WriteAttributeString("Name", dev.Device.Name);
                                        xml.WriteAttributeString("IpAddress", dev.IPAddress);
                                        xml.WriteAttributeString("Active", dev.Active.ToString());
                                        xml.WriteAttributeString("LibraryName", dev.Device.LibraryName);
                                        if (!string.IsNullOrEmpty(dev.Title))
                                            xml.WriteAttributeString(Client_Server_Interface.DeviceTreeItem.XmlTreeAttributeName.DEVICE_TITLE, dev.Title);
                                        xml.WriteEndElement();  //Device
                                    }

                                    xml.WriteEndElement();  //RTPS
                                }

                                xml.WriteEndElement();  //Region
                            }
                            xml.WriteEndElement();  //Regions
                            xml.WriteEndDocument();
                        }
                    }
                    catch (Exception)
                    {
                        return "err:" + ResourceManager.GetString("XML_Creating_Error");
                    }
                    //----------------
                }
            }
            catch (Exception)
            {
                return "err:" + ResourceManager.GetString("DBRequestError");
            }
            xmlFile = xmlWriter.ToString();
            return "ok";
        }

        public static string TreeToXml(string oblast, string xmlPath)
        {

            var deviceTree = new List<Oblast>(1);
            try
            {
                using (var s = NHibernateHelper.Create().Session)
                {
                    using (var tr = s.BeginTransaction())
                    {
                        if (oblast != "all")
                        {
                            var oblList = s.CreateQuery("FROM Oblast WHERE Name = :obl").SetString("obl", oblast).UniqueResult<Oblast>();
                            deviceTree.Add(oblList);
                        }
                        else
                        {
                            deviceTree = (List<Oblast>)s.CreateQuery("FROM Oblast").List<Oblast>();
                        }
                        tr.Commit();
                    }

                    //----------------

                    if (xmlPath == null)
                        return "err:" + ResourceManager.GetString("NoPath");
                    //string _deviceTreeNamespace = "http://tempuri.org/DeviceTree.xsd";

                    //XmlWriterSettings xmlSettings = new XmlWriterSettings();

                    try
                    {
                        using (var xml = XmlWriter.Create(xmlPath))
                        {
                            xml.WriteStartElement("Regions");
                            foreach (var obl in deviceTree)
                            {
                                xml.WriteStartElement("Region");
                                xml.WriteAttributeString("Name", obl.Name);
                                //xml.WriteElementString("RegionName", obl.Name);

                                foreach (RTPS rtps in obl.RTPSList)
                                {
                                    xml.WriteStartElement("RTPS");
                                    xml.WriteAttributeString("Name", rtps.Name);
                                    xml.WriteAttributeString("BLR", rtps.BLR.Name);
                                    xml.WriteAttributeString("Coordinates", rtps.Coordinates);

                                    foreach (Devices dev in rtps.DeviceList)
                                    {
                                        xml.WriteStartElement("Device");
                                        xml.WriteAttributeString("Name", dev.Device.Name);
                                        xml.WriteAttributeString("IpAddress", dev.IPAddress);
                                        xml.WriteAttributeString("Active", dev.Active.ToString());
                                        xml.WriteAttributeString("LibraryName", dev.Device.LibraryName);
                                        if(!string.IsNullOrEmpty(dev.Title))
                                            xml.WriteAttributeString(Client_Server_Interface.DeviceTreeItem.XmlTreeAttributeName.DEVICE_TITLE, dev.Title);
                                        xml.WriteEndElement();  //Device
                                    }

                                    xml.WriteEndElement();  //RTPS
                                }

                                xml.WriteEndElement();  //Region
                            }
                            xml.WriteEndElement();  //Regions
                            xml.WriteEndDocument();
                        }
                    }
                    catch (Exception)
                    {
                        return "err:" + ResourceManager.GetString("XML_Creating_Error");
                    }
                    //----------------
                }
            }
            catch (Exception)
            {
                return "err:" + ResourceManager.GetString("DBRequestError");
            }
            return "ok";
        }

        /// <summary>
        /// Формирует дерево устройств из данных, взятых с БД. (Область -> РТПС -> устройство).
        /// </summary>
        /// <returns>
        /// oblList[0].Name содержит информацию об ошибке, если операция не была выполнена успешно.
        /// тэг области - [главная РТПС]
        /// тэг ртпс - [блр];[координаты]
        /// тэг устройства - [ip-адрес]
        /// </returns>
        public static TreeNode[] GetTree()
        {
            var treeNodes = new TreeNode[6];

            var oblRepository = new DBRepository<Oblast>();
            var oblList = oblRepository.GetListStart();
            if (oblList[0].Name == "NODB")
            {
                treeNodes[0] = new TreeNode { Name = "err:" + ResourceManager.GetString("NoDBConnection") };
                return treeNodes;
            }
            var i = 0;
            foreach (var obl in oblList)
            {
                string tag = obl.MainRTPS == null ? "" : obl.MainRTPS.Name;
                var oblNode = new TreeNode(obl.Name) { Tag = tag };
                foreach (RTPS rtps in obl.RTPSList)
                {
                    var coord = new StringBuilder(15);
                    if (rtps.Coordinates != null && rtps.Coordinates.Length == 12)
                    {
                        coord.Append(rtps.Coordinates);
                        //coord.Append(rtps.Coordinates[0].ToString(CultureInfo.InvariantCulture) + rtps.Coordinates[1] + '°' + rtps.Coordinates[2] + rtps.Coordinates[3]
                        //    + '\'' + rtps.Coordinates[4] + rtps.Coordinates[5] + "\"N;");
                        //coord.Append(rtps.Coordinates[6].ToString(CultureInfo.InvariantCulture) + rtps.Coordinates[7] + '°' + rtps.Coordinates[8] + rtps.Coordinates[9]
                        //    + '\'' + rtps.Coordinates[10] + rtps.Coordinates[11] + "\"E;");
                    }

                    var rtpsNode = new TreeNode(rtps.Name) { Tag = rtps.BLR.Name + ";" + coord };
                    foreach (Devices dev in rtps.DeviceList)
                    {
                        var devnode = new TreeNode(dev.Device.Name) { Tag = dev.IPAddress + ";" + dev.Active };
                        rtpsNode.Nodes.Add(devnode);
                    }
                    oblNode.Nodes.Add(rtpsNode);
                }
                treeNodes[i++] = oblNode;
            }
            oblRepository.SessionClose();
            return treeNodes;
        }

        /// <summary>
        /// Формирует узел дерева, с основным узлом - регионом в виде объекта DeviceTreeItem.
        /// </summary>
        /// <param name="regionName">Узел дерева - регион.</param>
        /// <returns></returns>
        public static DeviceTreeItem GetDeviceTreeNode(string regionName)
        {
            var deviceTree = new DeviceTreeItem();
            var oblRepository = new DBRepository<Oblast>();
            var oblList = oblRepository.GetListStart();
            if (oblList.Count < 1)
            {
                throw new Exception("0 regions found");
            }
            if (oblList[0].Name == "NODB")
            {
                throw new Exception(ResourceManager.GetString("NoDBConnection"));
            }
            bool found = false;
            foreach (var obl in oblList)
            {
                if(obl.Name != regionName)
                    continue;
                found = true;
                //Заполнение данными об областях
                var oblInfo = new DeviceTreeItem.RegionInfo { Region = obl.Name };
                if (obl.MainRTPS != null)
                    oblInfo.MainStation = obl.MainRTPS.Name;
                var oblItem = new DeviceTreeItem { Header = obl.Name, AdditionalInfo = oblInfo };
                foreach (RTPS station in obl.RTPSList)
                {
                    //Заполнение данными о станциях
                    var stationInfo = new DeviceTreeItem.StationInfo
                    {
                        Station = station.Name,
                        BLR = station.BLR.Name,
                        Coordinates = station.Coordinates
                    };
                    var stationItem = new DeviceTreeItem { Header = station.Name, AdditionalInfo = stationInfo };
                    foreach (Devices device in station.DeviceList)
                    {
                        //Заполнение данными об устройствах
                        var deviceInfo = new DeviceTreeItem.DeviceInfo
                        {
                            Device = device.Device.Name,
                            IsActive = device.Active,
                            IpAddress = device.IPAddress,
                            Title = device.Title,
                        };
                        var deviceItem = new DeviceTreeItem { Header = device.Device.Name, AdditionalInfo = deviceInfo };
                        stationItem.AddSubItem(deviceItem);
                    }
                    oblItem.AddSubItem(stationItem);
                }
                deviceTree=oblItem;
            }
            if (!found)
                throw new DeviceTreeItem.RegionNotFoundException("Region " + regionName + " not found");
            oblRepository.SessionClose();
            return deviceTree;
        }

        /// <summary>
        /// Формирует дерево устройств в виде объектов DeviceTreeItem.
        /// </summary>
        /// <returns>Список регионов.</returns>
        public static List<DeviceTreeItem> GetDeviceTree()
        {
            var deviceTree = new List<DeviceTreeItem>();
            var oblRepository = new DBRepository<Oblast>();
            var oblList = oblRepository.GetListStart();
            if (oblList.Count < 1 || oblList[0].Name == "NODB")
            {
                throw new Exception(ResourceManager.GetString("NoDBConnection"));
            }
            foreach (var obl in oblList)
            {
                //Заполнение данными об областях
                var oblInfo = new DeviceTreeItem.RegionInfo {Region = obl.Name};
                if (obl.MainRTPS != null)
                    oblInfo.MainStation = obl.MainRTPS.Name;
                var oblItem = new DeviceTreeItem {Header = obl.Name, AdditionalInfo = oblInfo};
                foreach (RTPS station in obl.RTPSList)
                {
                    //Заполнение данными о станциях
                    var stationInfo = new DeviceTreeItem.StationInfo
                        {
                            Station = station.Name,
                            BLR = station.BLR.Name,
                            Coordinates = station.Coordinates
                        };
                    var stationItem = new DeviceTreeItem {Header = station.Name, AdditionalInfo = stationInfo};
                    foreach (Devices device in station.DeviceList)
                    {
                        //Заполнение данными об устройствах
                        var deviceInfo = new DeviceTreeItem.DeviceInfo
                            {
                                Device = device.Device.Name,
                                IsActive = device.Active,
                                IpAddress = device.IPAddress,
                                Title = device.Title
                            };
                        var deviceItem = new DeviceTreeItem {Header = device.Device.Name, AdditionalInfo = deviceInfo};
                        stationItem.AddSubItem(deviceItem);
                    }
                    oblItem.AddSubItem(stationItem);
                }
                deviceTree.Add(oblItem);
            }

            oblRepository.SessionClose();
            return deviceTree;
        }

        /// <summary>
        /// Формирует дерево доверенных адресов (Область -> ip-адрес)
        /// </summary>
        /// <returns></returns>
        public static TreeNode[] GetTrustedAddressTree()
        {
            var treeNodes = new TreeNode[6];
            var oblRepository = new DBRepository<Oblast>();
            var oblList = oblRepository.GetListStart();
            if (oblList[0].Name == "NODB")
            {
                treeNodes[0] = new TreeNode { Name = "err:" + ResourceManager.GetString("NoDBConnection") };
                return treeNodes;
            }
            int i = 0;
            foreach (Oblast oblast in oblList)
            {
                var oblNode = new TreeNode(oblast.Name);
                foreach (TrustedAddress address in oblast.TrustedAddressList)
                {
                    oblNode.Nodes.Add(address.Name);
                }
                treeNodes[i++] = oblNode;
            }
            oblRepository.SessionClose();
            return treeNodes;
        }

        public static Dictionary<string, List<string>> GetTrustedAddresses()
        {
            //var treeNodes = new TreeNode[6];
            var dret = new Dictionary<string, List<string>>();
            var oblRepository = new DBRepository<Oblast>();
            var oblList = oblRepository.GetListStart();
            if (oblList[0].Name == "NODB")
            {
                dret.Add("err:",new List<string>{ResourceManager.GetString("NoDBConnection")});
                return dret;
            }
            foreach (Oblast oblast in oblList)
            {
                var list = new List<string>();
                foreach (TrustedAddress address in oblast.TrustedAddressList)
                {
                    list.Add(address.Name);
                }
                dret.Add(oblast.Name, list);
            }
            oblRepository.SessionClose();
            return dret;
        }

        public static bool AddTrustedAddress(string ip, string oblast)
        {
            IPAddress ipAddress;
            if (!IPAddress.TryParse(ip, out ipAddress))
                return false;
            int oblId;
            try
            {
                oblId = (new DBRepository<Oblast>()).GetItem(oblast).Id;
            }
            catch (Exception)
            {
                return false;
            }
            var trustedAddress = new TrustedAddress { Idobl = oblId, Name = ipAddress.ToString() };
            return (new DBRepository<TrustedAddress>()).Add(trustedAddress);
        }

        public static bool AddStation(string stationName, string regionName, string blrName, string coordinates)
        {
            try
            {
                var newRtps = new RTPS
                    {
                        Name = stationName,
                        Idblr = (new DBRepository<BLR>()).GetItem(blrName).Id,
                        Idobl = (new DBRepository<Oblast>()).GetItem(regionName).Id,
                        Coordinates = coordinates
                    };
                return (new DBRepository<RTPS>()).Add(newRtps);
            }
            catch (Exception)
            {
                return false;
            }


        }
        
        /// <summary>
        /// Добавляет или замещает имеющуюся в базу картинку с заданным именем.
        /// </summary>
        /// <param name="name">Имя картинки.</param>
        /// <param name="path">Путь к картинке.</param>
        /// <returns></returns>
        public static bool AddReplacePicture(string name, byte[] fileData)
        {

            //var fileData = File.ReadAllBytes(path);
            var pict = new Pictures
                {
                    Name = name,
                    Value = fileData
                };
            var repository = new DBRepository<Pictures>();
            repository.Remove(name);
            return repository.Add(pict);
        }

        public static byte[] GetPicture(string name)
        {
            var pict = (new DBRepository<Pictures>()).GetItem(name);
            return pict != null ? pict.Value : new byte[0];
        }

        public static bool AddDevice(string name, string rtps, string ip)
        {
            var device = new Devices
                {
                    Idrtps = (new DBRepository<RTPS>()).GetItem(rtps).Id,
                    IPAddress = ip,
                    Iddevicelib = (new DBRepository<DevicesLibs>().GetItem(name).Id),
                    Active = true
                };
            return (new DBRepository<Devices>()).Add(device);
        }

        /// <summary>
        /// Провеяет, существует ли заданный ip-адрес в таблице устройств.
        /// </summary>
        /// <param name="ip"></param>
        /// <returns>true - указанный ip-адрес существует.</returns>
        public static bool CheckDeviceIp(string ip)
        {
            var item = (new DBRepository<Devices>()).GetList(string.Format("WHERE IPAddress = '{0}'", ip));
            return item.Any();
        }

        /// <summary>
        /// Обновляет необходимые данные в соответствующей таблице.
        /// </summary>
        /// <param name="table">Идентификатор таблицы. (Не название! Смотреть в коде, какой идентификатор соответствует какой таблице!)</param>
        /// <param name="pars">Параметры, соответствующие новой записи.</param>
        /// <returns>true - обновление прошло успешно.</returns>
        public static bool UpdateData(string table, params string[] pars)
        {
            switch (table)
            {
                #region region

                case "region":
                    //pars
                    //0 - Name
                    //1 - RTPS
                    if (pars.Length < 2)
                        return false;
                    var oblastList = new DBRepository<Oblast>();
                    Oblast obl;
                    int rtpsId;
                    try
                    {
                        obl = oblastList.GetItem(pars[0]);
                        rtpsId = (new DBRepository<RTPS>()).GetItem(pars[1]).Id;
                    }
                    catch (Exception)
                    {
                        return false;
                    }
                    obl.IdMainRTPS = rtpsId;
                    return oblastList.Update(obl);

                #endregion

                #region station

                case "station":
                    //pars: 
                    //0 - old Name; 
                    //1 - new Name
                    //2 - BLR;
                    //3 - Coordinates.
                    var rtpsList = new DBRepository<RTPS>();
                    if (pars.Length < 4 || pars[3].Length != 12)
                        return false;
                    RTPS rtps;
                    var oldName = pars[0];
                    int blrId;
                    try
                    {
                        rtps = rtpsList.GetItem(oldName);
                        blrId = (new DBRepository<BLR>()).GetItem(pars[2]).Id;
                    }
                    catch (Exception)
                    {
                        return false;
                    }
                    rtps.Name = pars[1];
                    rtps.Idblr = blrId;
                    rtps.Coordinates = pars[3];

                    //return rtpsList.Update(rtps);
                    return rtpsList.Update(rtps, oldName);

                #endregion

                #region device

                case "device":
                    //pars
                    //0 - Name
                    //1 - RTPS Name
                    //2 - IP
                    //3 - Active
                    //4 - Title
                    var deviceList = new DBRepository<Devices>();
                    if (pars.Length < 3)
                        return false;
                    Devices device;
                    try
                    {
                        int idRtps = (new DBRepository<RTPS>()).GetItem(pars[1]).Id;
                        //int idDevice = (new DBRepository<DevicesLibs>()).GetItem(pars[0]).Id;
                        device = deviceList.GetItem(pars[0], idRtps);
                    }
                    catch (Exception)
                    {
                        return false;
                    }
                    device.IPAddress = pars[2];
                    device.Active = bool.Parse(pars[3]);
                    device.Title = pars[4];
                    return deviceList.Update(device);

                #endregion

                #region option

                case "option":
                    //pars
                    //0 - Name
                    //1 - Value
                    var optionList = new DBRepository<Options>();
                    if (pars.Length < 2)
                        return false;
                    var option = new Options(pars[0], pars[1]);
                    return optionList.Update(option) || optionList.Add(option);
                //Сделать для настроек!!!

                #endregion

                default:
                    return false;
            }
        }

        /// <summary>
        /// Удаление записи по имени и, если необходимо, по idrtps.
        /// </summary>
        /// <param name="table">Идентификатор таблицы. (Не название! Смотреть в коде, какой идентификатор соответствует какой таблице!)</param>
        /// <param name="name">Имя записи.</param>
        /// <param name="rtpsName">Название РТПС, соответствующей записи.</param>
        /// <returns>true - запись успешно удалена.</returns>
        public static bool DeleteData(string table, string name, string rtpsName = "-_-")
        {
            switch (table)
            {
                case "region":
                    var oblastList = new DBRepository<Oblast>();
                    return oblastList.Remove(name);

                case "station":
                    var rtpsList = new DBRepository<RTPS>();
                    return rtpsList.Remove(name);

                case "device":
                    var deviceList = new DBRepository<Devices>();
                    return rtpsName != "-_-" && deviceList.Remove(name, rtpsName);

                case "trustedAddress":
                    var trustedAddressList = new DBRepository<TrustedAddress>();
                    return trustedAddressList.Remove(name);

                default:
                    return false;
            }
        }

        public static string GetUsers()
        {
            var list = new DBRepository<Users>().GetList();
            if (list.Count < 1)
                return "";
            if (list[0].Name == "NODB")
                return "err:" + ResourceManager.GetString("NoDBConnection");
            if (list[0].Name == "requesterror")
                return "err:" + ResourceManager.GetString("DBRequestError");
            return list.Aggregate("", (current, u) => current + u.ToString());
        }

        public static string[] GetServerLogList(DateTime dt1, DateTime dt2, int maxCount = -1, 
            string criteria = "", Dictionary<string, List<string>> pars = null)
        {
            List<ServerLog> list;
            var sb = new StringBuilder();
            sb.Append("FROM ServerLog as sl WHERE" +
                      " sl.Date BETWEEN :date1 AND :date2");
            sb.Append(criteria);
            using (var session = NHibernateHelper.Create().Session)
            {
                var q = session.CreateQuery(sb.ToString())
                                    .SetDateTime("date1", dt1)
                                    .SetDateTime("date2", dt2);
                if (maxCount != -1)
                    q.SetMaxResults(maxCount);
                if (pars != null && pars.Count > 0)
                {
                    foreach (var opt in pars )
                    {
                        q.SetParameterList(opt.Key, opt.Value);
                    }
                }
                list = (List<ServerLog>)q.List<ServerLog>();
            }
            //var list = new DBRepository<ServerLog>().GetList(criteria);
            var retlist = new List<string>();
            if (list.Count < 1)
                return retlist.ToArray();
            if (list[0].Name == "NODB")
            {
                retlist.Add("err:" + ResourceManager.GetString("NoDBConnection"));
                return retlist.ToArray();
            }
            if (list[0].Name == "requesterror")
            {
                retlist.Add("err:" + ResourceManager.GetString("DBRequestError"));
                return retlist.ToArray();
            }
            if (!list.Any())
                return retlist.ToArray();
            //list.Sort();
            foreach (var serverLog in list)
            {
                var str = new StringBuilder();
                string oblastName = serverLog.Oblast != null ? serverLog.Oblast.Name : "";
                string accessType = "";
                if (serverLog.AccessType != null)
                    if (serverLog.AccessType.Name != null)
                        accessType = serverLog.AccessType.Name;
                str.Append(serverLog.Login + ";" + accessType + ";" + oblastName + ";" +
                    serverLog.CategoryType.Name + ";" +
                    serverLog.Name + ";" + serverLog.Date.ToString(CultureInfo.InvariantCulture));
                retlist.Add(str.ToString());
            }
            return retlist.ToArray();

        }


        public static string[] GetServerLogCollection(DateTime dt1, DateTime dt2, int maxCount = -1,
            string criteria = "", Dictionary<string, List<string>> pars = null)
        {
            List<ServerLog> list;
            var sb = new StringBuilder();
            sb.Append("FROM ServerLog as sl WHERE" +
                      " sl.Date BETWEEN :date1 AND :date2");
            sb.Append(criteria);
            using (var session = NHibernateHelper.Create().Session)
            {
                var q = session.CreateQuery(sb.ToString())
                                    .SetDateTime("date1", dt1)
                                    .SetDateTime("date2", dt2);
                if (maxCount != -1)
                    q.SetMaxResults(maxCount);
                if (pars != null && pars.Count > 0)
                {
                    foreach (var opt in pars)
                    {
                        q.SetParameterList(opt.Key, opt.Value);
                    }
                }
                list = (List<ServerLog>)q.List<ServerLog>();
            }
            //var list = new DBRepository<ServerLog>().GetList(criteria);
            var retlist = new List<string>();
            if (list.Count < 1)
                return retlist.ToArray();
            if (list[0].Name == "NODB")
            {
                retlist.Add("err:" + ResourceManager.GetString("NoDBConnection"));
                return retlist.ToArray();
            }
            if (list[0].Name == "requesterror")
            {
                retlist.Add("err:" + ResourceManager.GetString("DBRequestError"));
                return retlist.ToArray();
            }
            if (!list.Any())
                return retlist.ToArray();
            //list.Sort();
            foreach (var serverLog in list)
            {
                var str = new StringBuilder();
                string oblastName = serverLog.Oblast != null ? serverLog.Oblast.Name : "";
                string accessType = "";
                if (serverLog.AccessType != null)
                    if (serverLog.AccessType.Name != null)
                        accessType = serverLog.AccessType.Name;
                str.Append(serverLog.Login + ";" + accessType + ";" + oblastName + ";" +
                    serverLog.CategoryType.Name + ";" +
                    serverLog.Name + ";" + serverLog.Date.ToString(CultureInfo.InvariantCulture));
                retlist.Add(str.ToString());
            }
            return retlist.ToArray();

        }

        public static List<string> GetRegionList()
        {
            var list = new DBRepository<Oblast>().GetList();
            var retlist = new List<string>();
            if (list[0].Name == "NODB")
            {
                retlist.Add("err:" + ResourceManager.GetString("NoDBConnection"));
                return retlist;
            }
            if (list[0].Name == "requesterror")
            {
                retlist.Add("err:" + ResourceManager.GetString("DBRequestError"));
                return retlist;
            }
            if (!list.Any())
                return retlist;
            retlist.AddRange(list.Select(oblast => oblast.Name));
            return retlist;
        }

        public static List<string> GetBlrList()
        {
            var list = new DBRepository<BLR>().GetList();
            var retlist = new List<string>();
            if (list[0].Name == "NODB")
            {
                retlist.Add("err:" + ResourceManager.GetString("NoDBConnection"));
                return retlist;
            }
            if (list[0].Name == "requesterror")
            {
                retlist.Add("err:" + ResourceManager.GetString("DBRequestError"));
                return retlist;
            }
            if (!list.Any())
                return retlist;
            retlist.AddRange(list.Select(blr => blr.Name));
            return retlist;
        }

        public static List<string> GetRTPSList()
        {
            var list = new DBRepository<RTPS>().GetList();
            var retlist = new List<string>();
            if (list[0].Name == "NODB")
            {
                retlist.Add("err:" + ResourceManager.GetString("NoDBConnection"));
                return retlist;
            }
            if (list[0].Name == "requesterror")
            {
                retlist.Add("err:" + ResourceManager.GetString("DBRequestError"));
                return retlist;
            }
            if (!list.Any())
                return retlist;
            retlist.AddRange(list.Select(rtps => rtps.Name));
            return retlist;
        }

        public static List<string> GetRegionStationsList(string regionName)
        {
            var stationList = new List<string>();
            var oblRepository = new DBRepository<Oblast>();
            var oblList = oblRepository.GetListStart();
            if (oblList.Count < 1)
            {
                throw new Exception("0 regions found");
            }
            if (oblList[0].Name == "NODB")
            {
                throw new Exception(ResourceManager.GetString("NoDBConnection"));
            }
            bool found = false;
            foreach (var obl in oblList)
            {
                if (obl.Name != regionName)
                    continue;
                found = true;
                //Заполнение данными об областях
                foreach (RTPS station in obl.RTPSList)
                {
                    //Заполнение данными о станциях
                    stationList.Add(station.Name);
                }
            }
            if (!found)
                throw new DeviceTreeItem.RegionNotFoundException("Region " + regionName + " not found");
            oblRepository.SessionClose();
            return stationList;
        }

        /// <summary>
        /// Возвращает список id - ipaddress всех устройств.
        /// </summary>
        /// <returns></returns>
        public static Dictionary<IPAddress, DeviceInfo> GetDeviceIps()
        {
            var ret = new Dictionary<IPAddress, DeviceInfo>();
            var list = new DBRepository<Devices>().GetList();
            if (list[0].Iddevicelib == -1)
            {
                throw new Exception(ResourceManager.GetString("NoDBConnection"));
            }
            if (list[0].Iddevicelib == -2)
            {
                throw new Exception(ResourceManager.GetString("DBRequestError"));
            }

            foreach (var device in list)
            {
                //ret.Add(device.Id.ToString(CultureInfo.InvariantCulture), IPAddress.Parse(device.IPAddress));
                //var t = new Tuple<int, int, bool>(device.Id, device.Iddevicelib, device.Active);
                var t = new DeviceInfo { DeviceName = device.Device.Name, DeviceRtps = device.RTPS.Name , Active = device.Active};
                ret.Add(IPAddress.Parse(device.IPAddress), t);
            }

            return ret;
        }

        public static List<string> GetDeviceList()
        {
            var list = new DBRepository<DevicesLibs>().GetList();
            var retlist = new List<string>();
            if (list[0].Name == "NODB")
            {
                retlist.Add("err:" + ResourceManager.GetString("NoDBConnection"));
                return retlist;
            }
            if (list[0].Name == "requesterror")
            {
                retlist.Add("err:" + ResourceManager.GetString("DBRequestError"));
                return retlist;
            }
            if (!list.Any())
                return retlist;
            retlist.AddRange(list.Select(rtps => rtps.Name));
            return retlist;
        }

        /// <summary>
        /// Возвращает ip устройства, имя его библиотеки, имя самого устройства и имя РТПС. Если ошибка, описание ошибки в string[1].
        /// </summary>
        /// <returns></returns>
        public static List<string[]> GetDeviceLibsList()
        {
            //var list = new DBRepository<DevicesLibs>().GetList();
            
            var list = new DBRepository<Devices>().GetList();
            var retlist = new List<string[]>(list.Count);
            if (list.Count < 1)
            {
                retlist.Add(new[] { "err:", ResourceManager.GetString("EmptyTable") + ": " + ResourceManager.GetString("DeviceList") });
                return retlist;
            }
            
            if (list[0].Iddevicelib == -1)
            {
                retlist.Add(new[] { "err:", ResourceManager.GetString("NoDBConnection") });
                return retlist;
            }
            if (list[0].Iddevicelib == -2)
            {
                retlist.Add(new[] { "err:", ResourceManager.GetString("DBRequestError") });
                return retlist;
            }
            if (!list.Any())
                return retlist;
            foreach (Devices device in list)
            {
                if(!device.Active)
                    continue;
                var dev = new DBRepository<DevicesLibs>().GetItem(device.Iddevicelib);
                if (dev == null)
                {
                    retlist.Add(new[] { "err:", ResourceManager.GetString("DBRequestError") });
                    return retlist;
                }
                var rtps = new DBRepository<RTPS>().GetItem(device.Idrtps);
                if (rtps == null)
                {
                    retlist.Add(new[] { "err:", ResourceManager.GetString("DBRequestError") });
                    return retlist;
                }
                retlist.Add(new[] { device.IPAddress, dev.LibraryName, dev.Name, rtps.Name });
            }
            
            return retlist;
        }

        /// <summary>
        /// Возвращает имя устройства, имя библиотеки.
        /// </summary>
        /// <returns></returns>
        public static List<string[]> GetLibs()
        {
            var list = new DBRepository<DevicesLibs>().GetList();
            // 0 - Device name
            // 1 - Library name
            return list.Select(libse => new[] {libse.Name, libse.LibraryName}).ToList();
        }

        /// <summary>
        /// Устанавливает значения для таблицы DevicesLibs из списка.
        /// </summary>
        /// <param name="devList">Список для таблицы.</param>
        /// <returns>True - если все получилось.</returns>
        public static void SetDevLibs(List<string[]> devList)
        {
            if (devList == null || devList.Count < 1)
                return;
            // 0 - Device name
            // 1 - Library name

            const string watched = "w";

            var devLibs = new DBRepository<DevicesLibs>();
            var list = devLibs.GetList();
            //Удаление
            foreach (var libse in list)
            {
                bool cont = false;
                foreach (var stringse in devList)
                {
                    if (stringse[0] == libse.Name)
                    {
                        cont = true;
                        //Помечаем просмотренные
                        stringse[2] = watched;
                        break;
                    }
                }
                if (!cont)
                    devLibs.Remove(libse);
            }

            //Добавление
            foreach (var stringse in devList)
            {
                if (string.IsNullOrEmpty(stringse[2]))
                {
                    devLibs.Add(new DevicesLibs(stringse[0], stringse[1]));
                }
            }
            return;
        }

        [System.Reflection.Obfuscation(Feature = "DllExport")]
        public static string[] GetDeviceLogList(string selectionString)
        {
            const int oblSplitNum = 0;
            const int blrSplitNum = 1;
            const int rtpsSplitNum = 2;
            const int devtypeSplitNum = 3;
            const int timeSplitNum = 4;

            string[] splitSelString = selectionString.Split(';');

            List<string> oblast, rtps, blr, devType;
            DateTime startTime;
            DateTime endTime;

            try
            {
                oblast = MakeParameterList(splitSelString[oblSplitNum], "Oblast");
                rtps = MakeParameterList(splitSelString[rtpsSplitNum], "RTPS");
                blr = MakeParameterList(splitSelString[blrSplitNum], "BLR");
                devType = MakeParameterList(splitSelString[devtypeSplitNum], "DevicesLibs");
                var timeSplit = splitSelString[timeSplitNum].Split(',');
                startTime = DateTime.Parse(timeSplit[0]);
                endTime = DateTime.Parse(timeSplit[1]);
            }
            catch (Exception)
            {
                var errString = new[] {"err:" + ResourceManager.GetString("OperationError") };
                return errString;
            }

            IList<object[]> list;
            try
            {
                using (var session = NHibernateHelper.Create().Session)
                {
                    list = session.CreateQuery("SELECT obl.Name, blr.Name, devce.Name, rtps.Name, devlog.Severity, devlog.Name, devlog.Source, devlog.Details, devlog.Time, devlog.EndTime "
                    //list = session.CreateQuery("SELECT obl.Name, blr.Name, devce.Name, rtps.Name, devlog.Severity, devlog.Name, devlog.Source, devlog.Time, devlog.Details "
                                                                + "FROM DeviceLog as devlog "
                                                                + "JOIN devlog.Device as dev "
                                                                + "JOIN dev.Device as devce "
                                                                + "JOIN dev.RTPS as rtps "
                                                                + "JOIN rtps.Oblast as obl "
                                                                + "JOIN rtps.BLR as blr "
                                                                + "WHERE obl.Name IN (:oblast_list) "
                                                                + "AND blr.Name IN (:blr_list) "
                                                                + "AND rtps.Name IN (:rtps_list) "
                                                                + "AND devce.Name IN (:devtype_list) "
                                                                + "AND devlog.Time BETWEEN :time1 AND :time2").SetParameterList("oblast_list", oblast)
                                                                                                              .SetParameterList("blr_list", blr)
                                                                                                              .SetParameterList("rtps_list", rtps)
                                                                                                              .SetParameterList("devtype_list", devType)
                                                                                                              .SetDateTime("time1", startTime)
                                                                                                              .SetDateTime("time2", endTime).List<object[]>();
                }
            }
            catch (Exception)
            {
                string[] errString = new[] { "err:" + ResourceManager.GetString("OperationError") };
                return errString;
            }
            var selRes = new string[list.Count];
            for (int i = 0; i < list.Count; i++)
            {
                selRes[i] = String.Join(";", list[i]);
            }

            return selRes;
        }
        
        public static string GetAccessType(int id)
        {
            var access = new DBRepository<Access>().GetItem(id).Name;
            return access;
        }

        /// <summary>
        /// Получает все настройки ([имя параметра]:[значение параметра];)
        /// </summary>
        /// <returns></returns>
        public static string GetOptionsList()
        {
            var list = new DBRepository<Options>().GetList();
            string retlist = "";
            if (!list.Any())
            {
                retlist = "err:" + ResourceManager.GetString("EmptyTable") + ": Options";
                return retlist;
            }
            if (list[0].Name == "NODB")
            {
                retlist = "err:" + ResourceManager.GetString("NoDBConnection");
                return retlist;
            }
            if (list[0].Name == "requesterror")
            {
                retlist = "err:" + ResourceManager.GetString("DBRequestError");
                return retlist;
            }
            if (!list.Any())
                return retlist;
            return list.Aggregate(retlist, (current, option) => current + (option.Name + ":" + option.Value + ";"));

        }

        /// <summary>
        /// Получает из базы значение параметра по его имени
        /// </summary>
        /// <param name="optionName">Имя параметра, значение которого требуется получить.</param>
        /// <returns>Значение запрошенного параметра.</returns>
        public static string GetOptionValue(string optionName)
        {
            var ret = new DBRepository<Options>().GetItem(optionName);
            if (ret == null)
                return "err:can not get value";
            return ret.Value;
        }

        /// <summary>
        /// Добавляет новый параметр в базу или изменяет значение для существующего.
        /// </summary>
        /// <param name="optionName">Имя параметра.</param>
        /// <param name="optionValue">Значение параметра.</param>
        /// <returns>Информация о результате выполнения операции.</returns>
        public static string AddOrSetOptionValue(string optionName, string optionValue)
        {
            var opt = new Options(optionName, optionValue);
            var ret = new DBRepository<Options>();
            if (!ret.Update(opt))
                if (!ret.Add(opt))
                    return "err:can not create/update option: " + optionName;
            return "ok";
        }

        public static string Test()
        {
            //return T_VIPS.CallMethod("getlog", new[] {"192.168.2.249", "d:\\testl.csv"});
            
            return "";
        }

        /// <summary>
        /// Проверка зависимостей.
        /// </summary>
        /// <returns>ok - все зависимости установлены.</returns>
        static string CheckDependences()
        {
            const string path = "Resources\\Libs\\";
            if (!File.Exists(path + "MySql.Data.dll"))
                return "err:" + ResourceManager.GetString("FileNotFound") + " 'MySql.Data.dll'";
            if (!File.Exists(path + "Iesi.Collections.dll"))
                return "err:" + ResourceManager.GetString("FileNotFound") + " 'Iesi.Collections.dll'";
            if (!File.Exists(path + "NHibernate.dll"))
                return "err:" + ResourceManager.GetString("FileNotFound") + " 'NHibernate.dll'";
            if (!File.Exists(path + "NHibernate.Mapping.Attributes.dll"))
                return "err:" + ResourceManager.GetString("FileNotFound") + " 'NHibernate.Mapping.Attributes.dll'";
            if (!File.Exists("Resources\\hibernate.cfg.xml"))
                return "err:" + ResourceManager.GetString("FileNotFound") + " 'hibernate.cfg.xml'";
            return "ok";
        }

        /// <summary>
        /// Вызов метода по его названию из данной библиотеки. (Используется для вызова из win32 приложений)
        /// </summary>
        /// <param name="param">Название метода.</param>
        /// <param name="pars">Входные параметры.</param>
        /// <returns></returns>
        public static string CallMethod(string param, params object[] pars)
        {
            var ret = CheckDependences();
            if (ret != "ok")
                return ret;
            var type = typeof(DBwork);
            var methods = type.GetMethods();
            try
            {
                var method = methods.First(met => met.Name.Contains(param));
                var obj = Activator.CreateInstance(type);
                return method.Invoke(obj, pars).ToString();
            }
            catch (Exception ex)
            {
                if (ex.Message == "Sequence contains no matching element")
                    return "err:" + ResourceManager.GetString("UnknownMethod");
                return "err:" + ex.Message;
            }

            #region faka
            //            switch (param)
            //            {
            //                case "AddUser":
            //                    try
            //                    {
            //                        ret = AddUser(pars[0], pars[1], pars[2], pars[3]);
            //                        return ret;
            //                    }
            //                    catch(Exception ex)
            //                    {
            //                        if (ex is IndexOutOfRangeException)
            //                            return "err:Неверное количество аргументов"; 
            //                        return "err:" + ex.Message;
            //                    }
            //                case "DelUser":
            //                    try
            //                    {
            //                        ret = DelUser(pars[0]);
            //                        return ret;
            //                    }
            //                    catch (Exception ex)
            //                    {
            //                        if (ex is IndexOutOfRangeException)
            //                            return "err:Неверное количество аргументов";
            //                        return "err:" + ex.Message;
            //                    }
            //                case "UpdateUser":
            //                    try
            //                    {
            //                        ret = UpdateUser(pars[0], pars[1], pars[2], pars[3], pars[4]);
            //                        return ret;
            //                    }
            //                    catch (Exception ex)
            //                    {
            //                        if (ex is IndexOutOfRangeException)
            //                            return "err:Неверное количество аргументов";
            //                        return "err:" + ex.Message;
            //                    }
            //                case "CheckPassword":
            //                    try
            //                    {
            //                        ret = CheckPassword(pars[0], pars[1]);
            //                        return ret;
            //                    }
            //                    catch (Exception ex)
            //                    {
            //                        if (ex is IndexOutOfRangeException)
            //                            return "err:Неверное количество аргументов"; 
            //                        return "err:" + ex.Message;
            //                    }
            //                case "GetUsers":
            //                    /*try
            //                    {
            //                        ret = GetUsers();
            //                        return ret;
            //                    }
            //                    catch (Exception ex)
            //                    {
            //                        if (ex is IndexOutOfRangeException)
            //                            return "err:Неверное количество аргументов";
            //                        return "err:" + ex.Message;
            //                    }*/
            //                case "MakeXML":
            //                    try
            //                    {
            //                        ret = MakeXml(pars[0], pars[1]);
            //                        return ret;
            //                    }
            //                    catch (Exception ex)
            //                    {
            //                        if (ex is IndexOutOfRangeException)
            //                            return "err:Неверное количество аргументов";
            //                        return "err:" + ex.Message;
            //                    }
            //                default:
            //                    return "err:Метод не найден";
            //            }
            #endregion
        }

        public static string SaveServerLog(string login, string access, string oblast, int category, string eventName, DateTime date)
        {
            var obl = new DBRepository<Oblast>();
            int? idobl;
            try
            {
                idobl = obl.GetItem(oblast).Id;
            }
            catch
            {
                idobl = null;
            }
            var serverLog = new DBRepository<ServerLog>();
            ServerLog servLog;

            int idacccess = -1;
            int? ida = null;
            if(int.TryParse(access, out idacccess))
                ida = idacccess;
            try
            {
                servLog = new ServerLog(login, ida, idobl, category, eventName, date);
            }
            catch
            {
                return "err:" + ResourceManager.GetString("WrongParameters");
            }

            return serverLog.Add(servLog) ? "ok" : "err:" + ResourceManager.GetString("OperationError");
        }

        #region не проверяет повторы!!!

        public static string UpdateBD_FromCSV1(string csvFilePath)
        {
            //Получаем необходимые данные из названия файла
            var path = csvFilePath.Split('\\');
            string fileName = path[path.Length - 1];
            var split = fileName.Split('_');
            string rtpsName = split[0];
            string devType = split[2].Split('.')[0];

            int devId;
            try
            {
                var rtps = new DBRepository<RTPS>();
                int idrtps = rtps.GetItem(rtpsName).Id;
                var device = new DBRepository<Devices>();
                devId = device.GetItem(devType, idrtps).Id;
            }
            catch (Exception) { return "err:" + ResourceManager.GetString("OperationError"); }

            DateTime minDate;
            List<DeviceLog> strList = FileToList(csvFilePath, devId, out minDate);
            if (strList.Count < 1)
                return "ok";
            if (strList[0].Name.Contains("err:"))
                return strList[0].Name;
            var devLog = new DBRepository<DeviceLog>();
            bool isAdded = devLog.AddRange(strList);
            if (!isAdded) { return "err:" + ResourceManager.GetString("OperationError"); }

            return "ok";

            //if (strList[0].Severity.Substring(0, 4) == "err:") { return strList[0].Severity; }

            //var devLog = new DBRepository<DeviceLog>();
            //string criteria = "WHERE Time >= '" + minDate.ToString("yyyy-MM-dd HH:mm:ss") + "'";
            //List<DeviceLog> dBlist = devLog.GetList(criteria);
            //if (dBlist.Count != 0 && dBlist[0].Name.Contains("requesterror")) { return "err:" + ResourceManager.GetString("DBRequestError"); }
            //if (dBlist.Count != 0 && dBlist[0].Name.Contains("NODB")) { return "err:" + ResourceManager.GetString("NoDBConnection"); }

            //var insertList = new List<DeviceLog>();
            //if (dBlist.Count == 0)
            //{
            //    insertList.Add(strList[0]);
            //    dBlist.Add(strList[0]);
            //}
            //foreach (DeviceLog str in strList)
            //{
            //    int i = 0;
            //    foreach (DeviceLog db in dBlist)
            //    {
            //        if (str.Name == db.Name)
            //        {
            //            if (str.Time == db.Time)
            //            {
            //                if (str.DevId == db.DevId)
            //                {
            //                    break;
            //                }
            //            }//if (str.Time == db.Time)
            //        }//if (str.Name == db.Name)

            //        {
            //            i++;
            //            if (i == dBlist.Count)
            //            {
            //                insertList.Add(str);
            //                dBlist.Add(str);
            //                break;
            //            }
            //        }
            //    }//foreach (DeviceLog db in DBlist)
            //} //foreach (DeviceLog str in strList)

            //bool isAdded = devLog.AddRange(insertList);
            //if (!isAdded) { return "err:" + ResourceManager.GetString("OperationError"); }

            //return "ok";
        }

        public static string UpdateBD_FromCSV(string csvFilePath)
        {
            //DateTime d1 = DateTime.Now;
            //Получаем необходимые данные из названия файла
            var path = csvFilePath.Split('\\');
            string fileName = path[path.Length - 1];
            var split = fileName.Split('_');
            string rtpsName = split[0];
            string devType = split[2].Split('.')[0];

            int devId;
            try
            {
                var rtps = new DBRepository<RTPS>();
                int idrtps = rtps.GetItem(rtpsName).Id;
                var device = new DBRepository<Devices>();
                devId = device.GetItem(devType, idrtps).Id;
            }
            catch (Exception) { return "err:" + ResourceManager.GetString("OperationError"); }

            DateTime minDate;
            List<DeviceLog> strList = FileToList(csvFilePath, devId, out minDate);
            if (strList.Count < 1)
                return "ok";
            if (strList[0].Name.Contains("err:"))
                return strList[0].Name;
            var devLog = new DBRepository<DeviceLog>();
            //List<DeviceLog> addItems;
            var isFound = devLog.FindExistingRowsInDevLogs(strList);
            if (!isFound) { return "err:" + ResourceManager.GetString("OperationError"); }
            //bool isAdded = devLog.AddRange(addItems);
            //if (!isAdded) { return "err:" + ResourceManager.GetString("OperationError"); }
            //DateTime d2 = DateTime.Now;
            //TimeSpan ts = d2 - d1;
            return "ok";
        }

        private static List<DeviceLog> FileToList(string csvFilePath, int devId, out DateTime minDate)
        {
            minDate = DateTime.Now;

            //Считываем файл
            string[] str;
            try
            {
                str = File.ReadAllLines(csvFilePath, Encoding.GetEncoding("Windows-1251"));
            }
            catch (Exception)
            {
                var err = "err:" + ResourceManager.GetString("FileCantRead") + ": " + csvFilePath;
                var errObj = new DeviceLog {Name = "err:" + err + ": " + csvFilePath};
                var errList = new List<DeviceLog> { errObj };
                return errList;
            }

            var strList = new List<DeviceLog>();
            for (int i = 1; i < str.Length; i++)
            {
                //str[i] = String.Join(";", str[i], devId.ToString(CultureInfo.InvariantCulture));
                if (str[i][str[i].Length - 1] == ';')
                {
                    str[i].Remove(str[i].Length - 1, 1);
                    //str[i] += devId.ToString(CultureInfo.InvariantCulture);
                }
                /*else
                {
                    str[i] = String.Join(";", str[i], devId.ToString(CultureInfo.InvariantCulture));
                }*/
                string[] spl = str[i].Split(';');
                if(spl.Length < 2) 
                    continue;
                var newDevListObj = new DeviceLog();
                try
                {
                    newDevListObj = new DeviceLog(spl, devId);
                }
                catch
                {
                    
                }
                strList.Add(newDevListObj);
                if (i == 1)
                    minDate = newDevListObj.Time;
            }
            return strList;
        }

        private static List<string> MakeParameterList(string selSubstring, string className)
        {
            var paramList = new List<string>();
            if (selSubstring.Contains("Все") || selSubstring == "")//Изменить здесь, в случае, если строка не будет содержать "Все"
                try
                {
                    using (var session = NHibernateHelper.Create().Session)
                    {
                        paramList = (List<string>)session.CreateQuery("SELECT Name FROM " + className).List<string>();
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            else
                paramList.AddRange(selSubstring.Split(','));

            return paramList;
        }

        #endregion
    }

}
